<template>
  <div class="p-2">
    <transition :enter-active-class="proxy?.animate.searchAnimate.enter" :leave-active-class="proxy?.animate.searchAnimate.leave">
      <div v-show="showSearch" class="mb-[10px]">
        <el-card shadow="hover">
          <el-form ref="queryFormRef" :model="queryParams" :inline="true">
            <el-form-item label="帖子id" prop="postsId">
              <el-input v-model="queryParams.postsId" placeholder="请输入帖子id" clearable @keyup.enter="handleQuery" />
            </el-form-item>
            <el-form-item label="评论用户" prop="userId">
              <el-input v-model="queryParams.userId" placeholder="请输入评论用户id" clearable @keyup.enter="handleQuery" />
            </el-form-item>
            <el-form-item label="父级评论" prop="parentId">
              <el-input v-model="queryParams.parentId" placeholder="请输入父级评论id" clearable @keyup.enter="handleQuery" />
            </el-form-item>
            <el-form-item label="评论目标用户" prop="replyUserId">
              <el-input v-model="queryParams.replyUserId" placeholder="请输入评论目标用户id;" clearable @keyup.enter="handleQuery" />
            </el-form-item>
            <el-form-item label="是否置顶" prop="topFlag">
              <el-select v-model="queryParams.topFlag" placeholder="请选择是否置顶" clearable>
                <el-option v-for="dict in sys_yes_no" :key="dict.value" :label="dict.label" :value="dict.value"/>
              </el-select>
            </el-form-item>
            <el-form-item label="点赞数" prop="likeCount">
              <el-input v-model="queryParams.likeCount" placeholder="请输入点赞数" clearable @keyup.enter="handleQuery" />
            </el-form-item>
            <el-form-item>
              <el-button type="primary" icon="Search" @click="handleQuery">搜索</el-button>
              <el-button icon="Refresh" @click="resetQuery">重置</el-button>
            </el-form-item>
          </el-form>
        </el-card>
      </div>
    </transition>

    <el-card shadow="never">
      <template #header>
        <el-row :gutter="10" class="mb8">
          <el-col :span="1.5">
            <el-button type="primary" plain icon="Plus" @click="handleAdd()" v-hasPermi="['comment:commentPosts:add']">新增</el-button>
          </el-col>
          <el-col :span="1.5">
            <el-button type="info" plain icon="Sort" @click="handleToggleExpandAll">展开/折叠</el-button>
          </el-col>
          <right-toolbar v-model:showSearch="showSearch" @queryTable="getList"></right-toolbar>
        </el-row>
      </template>
      <el-table
        ref="commentPostsTableRef"
        v-loading="loading"
        :data="commentPostsList"
        row-key="commentId"
        :default-expand-all="isExpandAll"
        :tree-props="{ children: 'children', hasChildren: 'hasChildren' }"
      >
        <el-table-column label="帖子id" prop="postsId" />
        <el-table-column label="评论用户id" align="center" prop="userId" />
        <el-table-column label="父级评论id" align="center" prop="parentId" />
        <el-table-column label="评论目标用户id;" align="center" prop="replyUserId" />
        <el-table-column label="内容" align="center" prop="content" />
        <el-table-column label="是否置顶" align="center" prop="topFlag">
          <template #default="scope">
            <dict-tag :options="sys_yes_no" :value="scope.row.topFlag"/>
          </template>
        </el-table-column>
        <el-table-column label="点赞数" align="center" prop="likeCount" />
        <el-table-column label="备注" align="center" prop="remark" />
        <el-table-column label="操作" align="center" class-name="small-padding fixed-width">
          <template #default="scope">
            <el-tooltip content="修改" placement="top">
              <el-button link type="primary" icon="Edit" @click="handleUpdate(scope.row)" v-hasPermi="['comment:commentPosts:edit']" />
            </el-tooltip>
            <el-tooltip content="新增" placement="top">
              <el-button link type="primary" icon="Plus" @click="handleAdd(scope.row)" v-hasPermi="['comment:commentPosts:add']" />
            </el-tooltip>
            <el-tooltip content="删除" placement="top">
              <el-button link type="primary" icon="Delete" @click="handleDelete(scope.row)" v-hasPermi="['comment:commentPosts:remove']" />
            </el-tooltip>
          </template>
        </el-table-column>
      </el-table>
    </el-card>
    <!-- 添加或修改文章评论对话框 -->
    <el-dialog :title="dialog.title" v-model="dialog.visible" width="800px" append-to-body>
      <el-form ref="commentPostsFormRef" :model="form" :rules="rules" label-width="80px">
        <el-form-item label="帖子" prop="postsId">
          <el-input v-model="form.postsId" placeholder="请输入帖子id" />
        </el-form-item>
        <el-form-item label="评论用户" prop="userId">
          <el-input v-model="form.userId" placeholder="请输入评论用户id" />
        </el-form-item>
        <el-form-item label="父级评论" prop="parentId">
          <el-tree-select
            v-model="form.parentId"
            :data="commentPostsOptions"
            :props="{ value: 'commentId', label: 'userId', children: 'children' }"
            value-key="commentId"
            placeholder="请选择父级评论id"
            check-strictly
          />
        </el-form-item>
        <el-form-item label="评论目标" prop="replyUserId">
          <el-input v-model="form.replyUserId" placeholder="请输入评论目标用户id;" />
        </el-form-item>
        <el-form-item label="内容">
          <editor v-model="form.content" :min-height="192"/>
        </el-form-item>
        <el-form-item label="是否置顶" prop="topFlag">
          <el-radio-group v-model="form.topFlag">
            <el-radio
              v-for="dict in sys_yes_no"
              :key="dict.value"
              :value="dict.value"
            >{{dict.label}}</el-radio>
          </el-radio-group>
        </el-form-item>
        <el-form-item label="点赞数" prop="likeCount">
          <el-input v-model="form.likeCount" placeholder="请输入点赞数" />
        </el-form-item>
        <el-form-item label="备注" prop="remark">
          <el-input v-model="form.remark" placeholder="请输入备注" />
        </el-form-item>
      </el-form>
      <template #footer>
        <div class="dialog-footer">
          <el-button :loading="buttonLoading" type="primary" @click="submitForm">确 定</el-button>
          <el-button @click="cancel">取 消</el-button>
        </div>
      </template>
    </el-dialog>
  </div>
</template>

<script setup name="CommentPosts" lang="ts">
import { listCommentPosts, getCommentPosts, delCommentPosts, addCommentPosts, updateCommentPosts } from "@/api/comment/commentPosts";
import { CommentPostsVO, CommentPostsQuery, CommentPostsForm } from '@/api/comment/commentPosts/types';

type CommentPostsOption = {
  commentId: number;
  userId: string;
  children?: CommentPostsOption[];
}

const { proxy } = getCurrentInstance() as ComponentInternalInstance;;

const { sys_yes_no } = toRefs<any>(proxy?.useDict('sys_yes_no'));

const commentPostsList = ref<CommentPostsVO[]>([]);
const commentPostsOptions = ref<CommentPostsOption[]>([]);
const buttonLoading = ref(false);
const showSearch = ref(true);
const isExpandAll = ref(true);
const loading = ref(false);

const queryFormRef = ref<ElFormInstance>();
const commentPostsFormRef = ref<ElFormInstance>();
const commentPostsTableRef = ref<ElTableInstance>()

const dialog = reactive<DialogOption>({
    visible: false,
    title: ''
});


const initFormData: CommentPostsForm = {
    commentId: undefined,
    postsId: undefined,
    userId: undefined,
    parentId: undefined,
    replyUserId: undefined,
    content: undefined,
    topFlag: undefined,
    likeCount: undefined,
    remark: undefined
}

const data = reactive<PageData<CommentPostsForm, CommentPostsQuery>>({
  form: {...initFormData},
  queryParams: {
    postsId: undefined,
    userId: undefined,
    parentId: undefined,
    replyUserId: undefined,
    content: undefined,
    topFlag: undefined,
    likeCount: undefined,
    params: {
    }
  },
  rules: {
    commentId: [
      { required: true, message: "对象存储主键不能为空", trigger: "blur" }
    ],
    postsId: [
      { required: true, message: "帖子id不能为空", trigger: "blur" }
    ],
    userId: [
      { required: true, message: "评论用户id不能为空", trigger: "blur" }
    ],
    parentId: [
      { required: true, message: "父级评论id不能为空", trigger: "blur" }
    ],
    content: [
      { required: true, message: "内容不能为空", trigger: "blur" }
    ],
  }
});

const { queryParams, form, rules } = toRefs(data);

/** 查询文章评论列表 */
const getList = async () => {
  loading.value = true;
  const res = await listCommentPosts(queryParams.value);
  const data = proxy?.handleTree<CommentPostsVO>(res.data, "commentId", "parentId");
  if (data) {
    commentPostsList.value = data;
    loading.value = false;
  }
}

/** 查询文章评论下拉树结构 */
const getTreeselect = async () => {
  const res = await listCommentPosts();
  commentPostsOptions.value = [];
  const data: CommentPostsOption = { commentId: 0, userId: '顶级节点', children: [] };
  data.children = proxy?.handleTree<CommentPostsOption>(res.data, "commentId", "parentId");
  commentPostsOptions.value.push(data);
}

// 取消按钮
const cancel = () => {
  reset();
  dialog.visible = false;
}

// 表单重置
const reset = () => {
  form.value = {...initFormData}
  commentPostsFormRef.value?.resetFields();
}

/** 搜索按钮操作 */
const handleQuery = () => {
  getList();
}

/** 重置按钮操作 */
const resetQuery = () => {
  queryFormRef.value?.resetFields();
  handleQuery();
}

/** 新增按钮操作 */
const handleAdd = (row?: CommentPostsVO) => {
  reset();
  getTreeselect();
  if (row != null && row.commentId) {
    form.value.parentId = row.commentId;
  } else {
    form.value.parentId = 0;
  }
  dialog.visible = true;
  dialog.title = "添加文章评论";
}

/** 展开/折叠操作 */
const handleToggleExpandAll = () => {
  isExpandAll.value = !isExpandAll.value;
  toggleExpandAll(commentPostsList.value, isExpandAll.value)
}

/** 展开/折叠操作 */
const toggleExpandAll = (data: CommentPostsVO[], status: boolean) => {
  data.forEach((item) => {
    commentPostsTableRef.value?.toggleRowExpansion(item, status)
    if (item.children && item.children.length > 0) toggleExpandAll(item.children, status)
  })
}

/** 修改按钮操作 */
const handleUpdate = async (row: CommentPostsVO) => {
  reset();
  await getTreeselect();
  if (row != null) {
    form.value.parentId = row.parentId;
  }
  const res = await getCommentPosts(row.commentId);
  Object.assign(form.value, res.data);
  dialog.visible = true;
  dialog.title = "修改文章评论";
}

/** 提交按钮 */
const submitForm = () => {
  commentPostsFormRef.value?.validate(async (valid: boolean) => {
    if (valid) {
      buttonLoading.value = true;
      if (form.value.commentId) {
        await updateCommentPosts(form.value).finally(() => buttonLoading.value = false);
      } else {
        await addCommentPosts(form.value).finally(() => buttonLoading.value = false);
      }
      proxy?.$modal.msgSuccess("操作成功");
      dialog.visible = false;
      getList();
    }
  });
}

/** 删除按钮操作 */
const handleDelete = async (row: CommentPostsVO) => {
  await proxy?.$modal.confirm('是否确认删除文章评论编号为"' + row.commentId + '"的数据项？');
  loading.value = true;
  await delCommentPosts(row.commentId).finally(() => loading.value = false);
  await getList();
  proxy?.$modal.msgSuccess("删除成功");
}

onMounted(() => {
  getList();
});
</script>
